#!/usr/bin/env python
#coding=utf-8
import time
from BeautifulSoup import BeautifulSoup 
import urllib
import urllib2

def get_soup(code, year, quater):
    
    def get_soup_one_time(code, year, quater):
        url = 'http://biz.finance.sina.com.cn/company/history.php'
        
        symb = "sh%s"%code
        values = {'quarter': quater, 'symbol': symb, 'year': year}
        data = urllib.urlencode(values)
        req = urllib2.Request(url, data)
        response = urllib2.urlopen(req)
        the_page = response.read()
        
        return BeautifulSoup(the_page, fromEncoding='gb2312')
    
    import socket
    socket.setdefaulttimeout(10)
    while True:
        try:
            s = get_soup_one_time(code, year, quater) 
            return s
        except (socket.timeout,IOError), e:
            print code, year, quater
            print e
            time.sleep(0.05)

def get_histprice_from_page(soup):
    def get_histprice_from_row(r):
        # date,open,high,close,low,volume,amount
        hp = []
        cs = r.contents
        
        a = cs[0].a
        if not a:
            hp.append(cs[0].string)
        else:
            hp.append(cs[0].a.string)
        
        for c in cs[1:]:
            hp.append(c.string)
        return hp
        
    hp = []
    t = unicode('日期', 'u8')
    
    table = soup.find(text = t).parent.parent.parent
    contents = table.contents
    if len(contents) == 1:
        #print contents
        return None
    rows = contents[1:]
    rows.reverse()
    
    for r in rows:
        hp.append(get_histprice_from_row(r))
        
    return hp

def get_aquater_histprice(code, year, quater):
    s = get_soup(code, year, quater)
    data = get_histprice_from_page(s)
    return data

if __name__ == '__main__':
    # date,open,high,close,low,volume,amount
    
    code = '600000'
    year = '2007'
    qs = ['1','2','3']
    
    prices = []
    
    for q in qs:
        data = get_aquater_histprice(code, year, q)
        prices = prices + data
        
    for r in prices:
        for i in r:
            print i, '\t',
        print 